/*
 * Copyright (c) 2007-2008, Thomas Krause (tho.krause@gmail.com)
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *     * Neither the name of gidoo nor the names of its contributors may be used to
 *       endorse or promote products derived from this software without specific
 *       prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.gidoo.cms.admin.addins;

import org.gidoo.cms.helper.Crypto;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.Model;
import org.apache.wicket.validation.validator.EmailAddressValidator;
import org.gidoo.cms.GidooCMS;
import org.gidoo.cms.admin.AdminPage;
import org.gidoo.cms.data.RegisteredUser;
import org.gidoo.cms.dbconnection.DatabaseConnectionException;

/**
 * A panel where you can adminstrate all users.
 * Implemented stuff so on: <br>
 * - adding new user
 * @author Thomas
 */
public class UsersPanel extends AddInPanel
{
  
  Form formNewUser;
  TextField txtNewUser;
  TextField txtRealName;
  TextField txtEMail;
  PasswordTextField txtPassword1;
  PasswordTextField txtPassword2;
  CheckBox cbIsAdmin;
  Button btNewUser;
  
  AdminPage theParent;
  
  /** Creates a new instance of UsersPanel */
  public UsersPanel(String id, AdminPage parent)
  {
    super(id);
    this.theParent = parent;
    
    formNewUser = new Form("formNewUser");
    add(formNewUser);
    
    txtNewUser = new TextField("txtNewUser", new Model(""));
    txtRealName = new TextField("txtRealName", new Model(""));
    txtEMail = new TextField("txtEMail", new Model(""));
    txtPassword1 = new PasswordTextField("txtPassword1", new Model(""));
    txtPassword2 = new PasswordTextField("txtPassword2", new Model(""));
    cbIsAdmin = new CheckBox("cbIsAdmin", new Model(new Boolean(false)));
    btNewUser = new Button("btNewUser", new Model(getString("addnewuser")))
    {
      @Override
      public void onSubmit()
      {
        addNewUser();
      }
    };
    
    txtNewUser.setRequired(true);
    txtNewUser.setLabel(new Model(getString("newusername")));
    txtRealName.setRequired(true);
    txtRealName.setLabel(new Model(getString("realname")));
    txtEMail.setRequired(true);
    txtEMail.add(EmailAddressValidator.getInstance());
    txtEMail.setLabel(new Model(getString("emailaddress")));
    txtPassword1.setLabel(new Model(getString("initialpassword")));
    txtPassword2.setLabel(new Model(getString("retype")));
    
    formNewUser.add(txtNewUser);
    formNewUser.add(txtRealName);
    formNewUser.add(txtEMail);
    formNewUser.add(txtPassword1);
    formNewUser.add(txtPassword2);
    formNewUser.add(cbIsAdmin);
    formNewUser.add(btNewUser);
    
  }
  
  protected void addNewUser()
  {
    
    if(txtPassword1.getValue() != null 
      && txtPassword1.getValue().equals(txtPassword2.getValue()))
    {
      try
      {        
        List<RegisteredUser> users = ((GidooCMS) getApplication()).getDb().getAllUsers();
        if(users.indexOf(txtNewUser.getModelObjectAsString()) > -1)
        {
          error(getString("userexists"));
          return;
        }
        
        RegisteredUser newUser = new RegisteredUser();
        newUser.setLoginName(txtNewUser.getModelObjectAsString());
        try
        {
          newUser.setPasswordHash(
            Crypto.calculateSHAHash(txtPassword1.getModelObjectAsString()));
        }
        catch(Exception ex)
        {
          error(getString("cryptoerror"));
        }
        newUser.setEmail(txtEMail.getModelObjectAsString());
        newUser.setFullName(txtRealName.getModelObjectAsString());
        newUser.setIsAdmin(((Boolean) cbIsAdmin.getModelObject()).booleanValue());
        
        ((GidooCMS) getApplication()).getDb().persist(newUser);
        
        theParent.updateDataAndView();
        
        info(getString("usercreated"));
      } catch (DatabaseConnectionException ex)
      {
        Logger.getLogger(UsersPanel.class.getName()).log(Level.SEVERE, null, ex);
        error(getString("dberror"));
      }
    }
    else
    {
      error(getString("passwordsnotequal"));
    }
  }
  
}
